package com.bear.richtext.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream

/**
 * 异步执行
 */
fun async(block: () -> Unit) {
    GlobalScope.launch(Dispatchers.Default) {
        block()
    }
}

/**
 * 在UI线程上执行
 */
fun uiThread(block: () -> Unit) {
    GlobalScope.launch(Dispatchers.Main) {
        block()
    }
}

internal object Tools {

    private var log: IRichTextLog = DefaultLog()
    private var imgLoad: ILoadImg = DefaultLoadImg()
    private var mReport:IReport? = null
    private val TAG = "Tools"

    fun ilog(tag: String, content: String) {
        log.ilog(tag, content)
    }

    fun elog(tag: String, content: String) {
        log.eLog(tag, content)
    }

    //从外部设置日志接口
    fun setLogInterface(Ilog: IRichTextLog) {
        log = Ilog
    }

    //从外部设置图片加载接口
    fun setImgLoadInterface(loadImg: ILoadImg) {
        imgLoad = loadImg
    }

    fun getImgLoad(): ILoadImg {
        return imgLoad
    }

    fun setReport(report:IReport){
        mReport = report
    }

    fun report(event: String, params: Map<String, String>) {
        async {
            mReport?.report(event, params)
        }
    }

    fun getScreenWidth(context: Context): Int {
        return context.resources.displayMetrics.widthPixels
    }


    /**
     * 图片压缩,
     */
    fun bitmapCompress(context: Context, originBitmap: Bitmap): Bitmap? {
        var bitmap: Bitmap? = null
        var bos: ByteArrayOutputStream? = null
        var ins: ByteArrayInputStream? = null
        try {
            val option = BitmapFactory.Options()
            option.inSampleSize = getSampleSize(context, originBitmap)
            bos = ByteArrayOutputStream()
            originBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos)
            ins = ByteArrayInputStream(bos.toByteArray())
            bitmap = BitmapFactory.decodeStream(ins, null, option)
        } catch (e: Exception) {
            elog(TAG, "bitmapCompress error:${e}")
        } finally {
            bos?.close()
            ins?.close()
        }
        return bitmap
    }

    fun getSampleSize(context: Context, bitmap: Bitmap): Int {
        val screenWidth = getScreenWidth(context)
        var inSampleSize = 1
        if (bitmap.width > screenWidth) {
            val halfWidth = bitmap.width / 2
            while ((halfWidth / inSampleSize) >= screenWidth) {
                inSampleSize *= 2
            }
        }
        return inSampleSize
    }
}